<template>
  <a-modal :width="1200" title="富文编辑器" v-model="visible" :maskClosable="false" @ok="getEditorData" @cancel="() => (visible = false)" :body-style="{padding:0}">
    <div id="sjht-wang-editor"></div>
  </a-modal>
</template>
<script>
import wangEditor from 'wangeditor'
export default {
  name: 'SjhtEditor',
  data() {
    return {
      editor: null,
      target: undefined,
      visible: false //是否弹出
    }
  },
  methods: {
    // 打开新建窗口
    open(content, target = null) {
      this.visible = true
      this.target = target
      this.$nextTick(function () {
        if (!this.editor) {
          const editor = new wangEditor('#sjht-wang-editor')
          editor.config.customAlert = (s, t) => {
            switch (t) {
              case 'success':
                this.$message.success(s)
                break
              case 'info':
                this.$message.info(s)
                break
              case 'warning':
                this.$message.warning(s)
                break
              case 'error':
                this.$message.error(s)
                break
              default:
                this.$message.info(s)
                break
            }
          }
          editor.config.height = 500
          editor.create() // 创建编辑器

          this.editor = editor
        } else this.editor.txt.clear()
        if (content) {
          this.editor.txt.html(content) // 重新设置编辑器内容
        }
      })
    },
    getEditorData() {
      // 通过代码获取编辑器内容
      let data = this.editor.txt.html()
      this.$emit('getdata', data, this.target) //事件
      this.visible = false
    }
  },
  beforeDestroy() {
    // 调用销毁 API 对当前编辑器实例进行销毁
    this.editor?.destroy()
    this.editor = null
  }
}
</script>